package me.keiwu.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.data.service.UserInfoBean;
import me.keiwu.pub.service.WXService;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.user.dao.UserDeliveryAddressDao;
import me.keiwu.user.domain.UserDeliveryAddress;
import me.keiwu.user.domain.UserForm;
import me.keiwu.user.service.UserDeliveryAddressService;
import me.keiwu.user.service.UserService;
import me.keiwu.user.util.ExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.HashMap;

@Transactional
@Service
public class UserDeliveryAddressServiceImpl implements UserDeliveryAddressService{


    @Autowired
    UserDeliveryAddressDao userDeliveryAddressDao;
    @Autowired
    private WXService wxService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExceptionUtil exceptionUtil;
    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public UserDeliveryAddress saveUserAddress(UserDeliveryAddress address) {
        return userDeliveryAddressDao.save(address);
    }

    @Override
    public boolean hasFilledAddress(Long userId) {
        return userDeliveryAddressDao.fillCountForUser(userId) > 0;
    }

    @Override
    public ResponseV2 sendDeliveryAddressTmpMsg(Long userId, String gift, String msg){
        UserInfoBean toUser = userService.getUserInfo(userId);
        UserForm userForm = userService.getOldestUserFormById(userId);
        if (toUser != null && userForm != null){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("formId", userForm.getFormId());
            map.put("templateMsgType",6);
            map.put("keyword2", gift);
            map.put("keyword3", msg);
            ResponseV2 resp = wxService.sendTemplateMsg(null, JSONObject.toJSONString(toUser),"pages/delivery/deliveryAddress",map);
            exceptionUtil.logError(this.getClass(), "sendDeliveryAddressTmpMsg", resp.getMsg());
            if (resp.getCode() == HttpStatus.OK.value() || resp.getCode() == 1) {
                userService.deleteUsedForm(userForm.getId());
                if (resp.getCode() == 1) {
                    exceptionUtil.logError(this.getClass(), "sendDeliveryAddressTmpMsg", "redo");
                    return sendDeliveryAddressTmpMsg(userId, gift, msg);
                }
            }
            return resp;
        }
        return ResponseV2.fail("no useable form id");
    }

    @Override
    public ResponseV2 clearTmpMsgRecord(String redisKey){
        return ResponseV2.ok(cacheUtil.clearTmpMsgRecord(redisKey));
    }
}
